package service

import (
	"context"
	"fmt"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"mini-gde/client"
	"mini-gde/model"
)

func ListPods(namespace string) []model.Pod {
	k8spods, err := client.Clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		fmt.Println("err ")
	}

	pods := []model.Pod{}
	for _, pod := range k8spods.Items {
		fmt.Println(pod.Name)
		tmp := model.Pod{
			Name:       pod.ObjectMeta.Name,
			Namespace:  pod.ObjectMeta.Namespace,
			Uid:        string(pod.ObjectMeta.UID),
			Images:     pod.Spec.Containers[0].Image,
			NodeName:   pod.Spec.NodeName,
			CreateTime: pod.CreationTimestamp.Format("2006-01-02 15:04:05"),
		}
		pods = append(pods, tmp)
	}
	return pods
}
func DeletePod(uid string) error {
	k8spods, err := client.Clientset.CoreV1().Pods("default").Get(context.TODO(), uid, metav1.GetOptions{})
	if err != nil {
		fmt.Println("err ")
	}
	if errors.IsNotFound(err) {
		fmt.Printf("Deployment not found\n")
	} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
		fmt.Printf("Error getting deployment%v\n", statusError.ErrStatus.Message)
	} else if err != nil {
		panic(err.Error())
	} else {
		fmt.Printf("Found deployment\n")
		name := k8spods.GetName()
		fmt.Println("name ->", name)
		err := client.Clientset.CoreV1().Pods(k8spods.Namespace).Delete(context.TODO(), k8spods.Name, metav1.DeleteOptions{})
		if err != nil {
			fmt.Println(err)
		}
	}
	return nil
}
